<?php
session_start();
Header("content-type: application/x-javascript");
require 'connection.php';
require 'util.php';
?>
var resultMoreInfoToClose = null;
function Results(){
  
  /*Creates a the map*/
  this.createMap = function(lat, lon){
    var myLatLng = new google.maps.LatLng(lat, lon);
    var mapOptions = {
        center: myLatLng,
        zoom: 13
      };
    var map = new google.maps.Map(this.mapCanvas, mapOptions); 
    return map;
  };
 
  this.createMarkers = function(resultArray, map){
    var markers = {};
    for(var i in resultArray){
      if(!resultArray.hasOwnProperty(i)){
        continue;
      }
      var myLatLng = new google.maps.LatLng(resultArray[i].position.latitude, resultArray[i].position.longitude);
      var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        anchorPoint: new google.maps.Point(0, -29)
      });
      marker.setIcon(/** @type {google.maps.Icon} */({
      url: resultArray[i].iconImage.path,
      size: new google.maps.Size(resultArray[i].iconImage.width, resultArray[i].iconImage.height),
      origin: new google.maps.Point(0, 0),
      anchor: new google.maps.Point(17, 34),
      scaledSize: new google.maps.Size(resultArray[i].iconImage.scaledWidth, resultArray[i].iconImage.scaledHeight)
      }));
      marker.setVisible(true);
      markers[resultArray[i].id] = marker;
      resultArray[i].marker = marker;
      resultArray[i].infoWindow = new InfoBox({
         content: resultArray[i].infoWindowString,
         disableAutoPan: false,
         maxWidth: resultArray[i].infoWindowData.width,
         pixelOffset: new google.maps.Size(resultArray[i].infoWindowData.pixelOffset.x, resultArray[i].infoWindowData.pixelOffset.y),
         //pixelOffset: new google.maps.Size(0, 0),
         zIndex: null,
         boxStyle: {},
        closeBoxMargin: "",
        closeBoxURL: "",
        infoBoxClearance: new google.maps.Size(1, 1)
    });
    var infobox = resultArray[i].infoWindow;
    var thisObj = this;
    var openInfoBox = function(i) {
        thisObj.closeInfoBox();
        var m = resultArray[i].marker;
        resultArray[i].infoWindow.open(map, m);
        google.maps.event.addListener(resultArray[i].infoWindow, 'domready', function() {
            initializeMoreInfoButtonInMap();
        });
        m.setVisible(false);
        thisObj.openedInfoBoxResultId = i;
    };
    var addEvent = function(i){
      google.maps.event.addListener(resultArray[i].marker, 'click', function(){
      debugger;
      openInfoBox(i);
      });
    };

    addEvent(i);
    }
    return markers;
  };

  this.createClusters = function(markers, map){
    var mcOptions = {gridSize: 50, maxZoom: 15};
    var markersArray = [];
    for(var key in markers){
      var i = 0;
      if(markers.hasOwnProperty(key)){
        markersArray[i++] = markers[key];
      }
    }
    var mc = new MarkerClusterer(map, markers, mcOptions);
  };
  this.createAutoComplete = function(map, placeInput){
      var thisObj = this;
      var autocomplete = new google.maps.places.Autocomplete(placeInput);
      google.maps.event.addListener(autocomplete, 'place_changed', function() {
      var place = autocomplete.getPlace();
      thisObj.userPosition.latitude = place.geometry.location.lat();
      thisObj.userPosition.longitude = place.geometry.location.lng();
      thisObj.changeLocationFromInput(place.address_components);
      thisObj.centerMapAfterChangeLocation = function()
      {
        debugger;
        if (!place.geometry) {
        return;
        }
        // If the place has a geometry, then present it on a map.
        if (place.geometry.viewport) {
          map.fitBounds(place.geometry.viewport);
        } else {
          map.setCenter(place.geometry.location);
          map.setZoom(17);  // Why 17? Because it looks good.
        }
      };
      
    });
    return this.autocomplete;
  };

  this.goTo = function(lat, lon, map, markerId){
    var latlon = new google.maps.LatLng(lat, lon);
    var thisObj = this;
    map.setCenter(latlon);
  };

  this.addGoTo = function(result, map){
    var mapLinkATagId = "#"+result.mapLinkId;
    var thisObj = this;
    $(mapLinkATagId).click(function(){
      debugger;
      if(resultMoreInfoToClose)
      {
        var bttn = $("a[id=moreInfoButton"+result.id.substring(1, result.id.length)+"]");
        if(bttn)
        {
          debugger;
          bttn.trigger("click");
        }
      }
      thisObj.goTo(result.position.latitude, result.position.longitude, thisObj.map, result.id);
      new google.maps.event.trigger( result.marker, 'click' );
    });
  };

  this.initialize = function(resultArray, mapCanvas, placeInput){
    debugger;
    this.resultArray = resultArray;
    this.openedInfoBoxResultId = "";
    this.mapCanvas = mapCanvas;
    this.placeInput = placeInput;

    //Print listings left side
    for(var i = 0; i<this.resultArray.length; i++)
    {
      $("#resultsContainer").append(this.resultArray[i].leftSideString);
    }

    this.map = this.createMap(this.userPosition.latitude, this.userPosition.longitude);
    var thisObj = this;
    google.maps.event.addListener(this.map, 'zoom_changed', function() {
        thisObj.closeInfoBox();
    });
    this.markers = this.createMarkers(resultArray, this.map);
    this.createClusters(this.markers, this.map);
    if(placeInput != null){
      this.createAutoComplete(this.map, placeInput);
    }
    for(var o in resultArray){
      if(!resultArray.hasOwnProperty(o)){
        continue;
      }
      this.addGoTo(resultArray[o], this.map);
    }
    var thisObj = this;
    /*var setUserLocation = function(pos){
      if(!pos){
        pos = {
          coords: {latitude: 51.524979,
          longitude: -0.129304}
        };
      }
      thisObj.userLocation = pos.coords;
      var myLatLng = new google.maps.LatLng(thisObj.userLocation.latitude, thisObj.userLocation.longitude);
      thisObj.map.setCenter(myLatLng);
    };*/
        
    initPage();
    if(this.centerMapAfterChangeLocation)
    {
      thisObj.centerMapAfterChangeLocation();
    }
    
  };

  this.closeInfoBox = function(){
    if(this.openedInfoBoxResultId === ""){
      return;
    }
    var theInfoBoxOpened = this.resultArray[this.openedInfoBoxResultId].infoWindow;
    var theMarkerHidden = this.resultArray[this.openedInfoBoxResultId].marker;
    theInfoBoxOpened.close();
    theMarkerHidden.setVisible(true);
  };
  this.getCityFromLocation = function(addressComponents)
  {
    debugger;
    var city = "London";
    for(var i = 0; i < addressComponents.length; i++)
    {
      if(addressComponents[i].types.indexOf("locality") != -1)
      {
        city = addressComponents[i].long_name;
        break;
      }
    }
    return city;
  };
  this.generateResultObject = function(resultRaw)
  {
    return {
      id: 'r'+resultRaw.encryptedPk ,
        divId: resultRaw.encryptedPk,
        mapLinkId: 'mapLink'+resultRaw.encryptedPk,
        position: {
          latitude: resultRaw.latitude, 
          longitude: resultRaw.longitude
        },
        iconImage: {
          path: 'img/marker.png',
          height:48,
          width:42,
          scaledHeight:48,
          scaledWidth:42
        },

        markerString: '',

        infoWindowString: '<div class=\"infoWindow2\" id=\"infoWindow_r'+resultRaw.encryptedPk+'\">'+
                 ' <div class=\"imageContainer\" style=\"background-image: url(\''+resultRaw.imageUrl+'\');\">'+
                  '</div>'+
                  '<div class=\"infoWindowContents\">'+
                   ' <div class=\"i-w-headingContainer\">'+
                    '  <p class=\"i-w-headingTitle ellipsis\">'+resultRaw.title+'</p><p class=\"i-w-price\">&#163;'+resultRaw.price+'</p>'+
                   ' </div>'+
                   ' <div class=\"i-w-body\">'+
                    '  <p class=\"ellipsis\">'+resultRaw.description+'</p>'+
                   ' </div>'+
                    '<div class=\"i-w-links\">'+
                      '<a class=\"moreInfoLink\" id=\"moreInfoLinkMap_'+resultRaw.encryptedPk+'\" href=\"#\">MORE INFO</a><a class=\"closeLink\" href=\"#\" onclick=\"window.results.closeInfoBox()\">X</a>'+
                    '</div>'+
                 ' </div>'+
                 ' <div class=\"i-w-pin\">'+
                 '   <div>'+
                      ' </div>'+
                       '<div>'+
                       '</div>'+
                     '</div>'+
                   '</div>',
        infoWindowData:{
          pixelOffset:{
            x:-30,
            y: -80
          },
          width:210
        },
        leftSideString: '<div class=\"result\" id=\"'+resultRaw.encryptedPk+'\">'+
                  '<div class=\"listing-image-container\">'+
                    '<img src=\"'+resultRaw.imageUrl+'\">'+
                    '</img>'+
                  '</div>'+
                  '<div class=\"result-info\">'+
                   ' <div class=\"result-info-head\">'+
                      '<span class=\"ellipsis\">'+resultRaw.title+'</span>'+
                      '<span>&#163;'+resultRaw.price+'</span>'+
                    '</div>'+
                    '<div class=\"result-info-suburb\">'+
                      '<p><span class=\"bold-text\">SUBURB:</span>'+resultRaw.district+'</p>'+
                   ' </div>'+
                    '<div class=\"result-info-description\">'+
                      '<p>'+resultRaw.description+'</p> '+
                    '</div>'+
                    '<div class=\"result-info-additional\">'+
                      (resultRaw.beds === '' ? '' : '<div class=\"beds\"><span class=\"icon\"></span><span>'+resultRaw.beds+'</span></div>')+
                    '</div>'+
                    '<div class=\"result-info-more\">'+
                      '<a id=\"mapLink'+resultRaw.encryptedPk+'\" href=\"#\">MAP</a>'+
                      '<a id=\"moreInfoButton'+resultRaw.encryptedPk+'\" class=\"more-info-button-open\" href=\"#\"></a>'+
                   ' </div>'+
                  '</div>'+
               ' </div>'
      };
  }
  this.load = function(location, cityName)
  {
    var thisObj = this;
    var cityName = cityName || this.getCityFromLocation(location.results[0]['address_components']);
    //Here I get the city
    var afterLoadLeftSide = function(response)
    {
      $("#resultsContainer").html("");
      var results = [];
      response = JSON.parse(response);
      for(var i = 0; i < response.length; i++)
      {
        results.push(thisObj.generateResultObject(response[i]));
      }
      var mapCanvas = document.getElementById('map-canvas');
      var placeInput = document.getElementById('place-input');
      thisObj.initialize(results, mapCanvas, placeInput);
      /*var center = results.map.getCenter();*/

    };
    var params = 
    {
      city: cityName,
      action: "getLeftSide"
    };
    var url = getURL("results.php");
    $.post(url, params, afterLoadLeftSide);
  };

  this.changeLocation = function(lat, lng)
  {
    debugger;
    
    var lat = lat || 51.524979;
    var lng = lng || -0.129304;
    this.userPosition = {
      latitude: lat,
      longitude: lng
    }
    var thisObj = this;
    var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lng+"&language=en";
    var afterLoadLocation = function(response)
    {
      thisObj.load(response);
      //afterLoad(response);
    };
    $.get(url, afterLoadLocation);
  };

  this.changeLocationFromInput = function(location)
  {
    var cityName = this.getCityFromLocation(location);
    this.load(null, cityName);
  };
}

function logout(){
  var form = document.getElementById("logoutForm");
  form.submit();
}

function load(){

//Load the results.
var resultObject = window.results = new Results();
if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function(pos){resultObject.changeLocation(pos.coords.latitude, pos.coords.longitude)});
  }
  resultObject.changeLocation();


 /*Retrieves the user location*/
/*
  var mapCanvas = document.getElementById('map-canvas');
  var placeInput = document.getElementById('place-input');
  window.results = new Results();
  results.initialize(resultArray, mapCanvas, placeInput, userLocation);
  var center = results.map.getCenter();
  */
}
google.maps.event.addDomListener(window, 'load', load);

function openInfoWindow(id){
  debugger;
  window.results.resultArray[id].infowindow.open(window.results.map, window.results.resultArray[id].marker);
  window.results.resultArray[id].markerWindow.close();
}

var filterOpened = false;
var initializeMoreInfoButtonInMap;
var filtersInitialized = false;
function initPage(){
  var minPrice=100;
  var maxPrice=2500;
  var minDistance = 0;
  var maxDistance = 100;
  var changeButtonColor = function(child){
    $(child).parent().children().each(function(){
    $(this).removeClass("blueButton2").addClass("blueButton");
    });
    $(child).addClass("blueButton2");

    if($(child).index() == 0){
      $("#arrow").css("left","150px");
    }else if($(child).index() == 1){
      $("#arrow").css("left","230px");
    }else if($(child).index() == 2){
      $("#arrow").css("left","310px");
    }else if($(child).index() == 3){
      $("#arrow").css("left","390px");
    }
  };
  var showFilters = function(){
    //$("#menu").slideDown(200);
   };
   var hideFilters = function(){
    /*if ((!$("#ui-datepicker-div").is(":visible") || $("#ui-datepicker-div").html() == "") && $("#n")) {
       $("#menu").slideUp(200);
       //$("#arrow").slideUp(200);
    }*/
   };
   var changePriceValue = function(inputRange, inputTextPriceValueID){
      var inputRangeValue = parseInt($(inputRange).val());
      $(inputTextPriceValueID).removeAttr('readonly');
      $(inputTextPriceValueID).val("£"+(minPrice + maxPrice * (inputRangeValue/100)).toFixed(0));
      $(inputTextPriceValueID).attr('readonly','readonly');
   };

  $("#left-buttons-container").children().each(function (){
    $(this).click(function(){changeButtonColor($(this));
    });
  });
  function displayOrCloseFilters(){
    debugger;
    if(!filterOpened)
    {
      $("#menuWrapper").addClass("open-filter");
      $(".filters-button-container").addClass("blue-background");
      $(".filters-button").addClass("open");
    }
    else
    {
      $("#menuWrapper").removeClass("open-filter");
      $(".filters-button-container").removeClass("blue-background");
      $(".filters-button").removeClass("open");
    }
    filterOpened = !filterOpened;
  }
  function initFilters()
  {
    filtersInitialized = true;
    $(".filters-button-container .filters-button").click(displayOrCloseFilters);
  $("#date input[type='text']").each(function(){$(this).datepicker({  
            inline: true,  
            showOtherMonths: true,  
            dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],  
        });});

  var initialPriceValue = parseInt($("#input-range-price").val());
  $("#input-range-price + p").width(170*(initialPriceValue/100));
  $("#priceValue").attr("value","£"+(minPrice + maxPrice * (initialPriceValue/100)));
  $("#priceValue").attr('readonly','readonly');
  $("#input-range-price").on("input change", function(){
    changePriceValue($(this), "#priceValue");
  });

  $("#all").change(function(){
    if($("#all").prop('checked') == true){
        $("#menu input[type='checkbox']").each(function(){
          $(this).prop('checked', true);
        });
    }else{
        $("#menu input[type='checkbox']").each(function(){
          $(this).prop('checked', false);
        });
    }
  });

  $('input[type="range"]').change(function () {
    var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min'));
    
    $(this).css('background-image',
                '-webkit-gradient(linear, left top, right top, '
                + 'color-stop(' + val + ', black), '
                + 'color-stop(' + val + ', #979797)'
                + ')'
                );
    $(this).css('background-image',
                '-moz-linear-gradient(left, '
                + 'black ' + (val*100) + '%, '
                + '#979797 ' + 0 + '%'
                + ')'
                );
    $(this).css('background-image',
                '-ms-linear-gradient(left, '
                + 'black ' + (val*100) + '%, '
                + '#979797 ' + 0 + '%'
                + ')'
                );
});

  }

  if(!filtersInitialized)
  {
    initFilters();
  }
  

function closeMoreInfoWindow()
{
  $("#moreInfoPanel").css('left', "1300px");
  resultMoreInfoToClose = null;
}
function openMoreInfoWindow(thisObj)
{
  if($(thisObj).hasClass("more-info-button-open")){
    if(resultMoreInfoToClose){
      $(resultMoreInfoToClose).removeClass("more-info-button-close");
      $(resultMoreInfoToClose).addClass("more-info-button-open");
      
    } 
    getAdditionalInformation(thisObj);
    
    $(thisObj).removeClass("more-info-button-open");
    $(thisObj).addClass("more-info-button-close");
    
    resultMoreInfoToClose = thisObj;
  }else{
    $(thisObj).removeClass("more-info-button-close");
    $(thisObj).addClass("more-info-button-open");
    
    closeMoreInfoWindow();
  }
}
$("a[id^=moreInfoButton]").each(function(){
  var thisObj = this;
  $(thisObj).click(function(){
    openMoreInfoWindow(thisObj);
  });
});
debugger;
initializeMoreInfoButtonInMap = function()
{
  $("a[id^=moreInfoLinkMap]").each(function(){
    var thisObj = this;
    $(thisObj).off("click");
    $(thisObj).on("click",function(){
      debugger;
      var buttonId = $(thisObj).attr("id");
      $("#moreInfoButton"+buttonId.substr(buttonId.length - 10)).trigger("click");
      //getAdditionalInformation(thisObj);
    });
  });
};

var updateFrostingPanel = function() {
    $('.module').each(function(index) {
      var module = {};

      module.element = $(this);
      module.background = $('.module-background', this);

      modules.push(module);
    });
    
    // Configure Background On All Modules
    // -----------------------------------
    var module = null,
        topOffset,
        leftOffset;

    // Calculate Offsets For All Modules
    for(var m = 0; m < modules.length; m++) {
        module = modules[m];
        topOffset = 0 - $(module.element).offset().top;
        leftOffset = 0 - $(module.element).offset().left;

        // Calculate Offsets
        $(module.background).css({
            '-webkit-transform':'translate3d(' + leftOffset + 'px' + ',' + topOffset + 'px' + ',' + 0 + ')',
            'transform': 'translate3d(' + leftOffset + 'px' + ',' + topOffset + 'px' + ',' + 0 + ')'
        });

        // Resize Module Background Image To Match Main Background Image
        $('img', module.background).css({
            'width': backgroundImageWidth + 'px ',
            'height': backgroundImageHeight + 'px'
        });
    }
}
function getAdditionalInformation(element){
  //showLoadingLayer();
  var resultId = $(element).attr("id");
  var url = getURL("getAdditionalInformation.php");
  var showAdditionalInfo = function(htmlCode){
    //hideLoadingLayer();
    var additionalInformationPanel = new AdditionalInformationPanel(htmlCode, resultId);
    var closeFx = function()
    {
      $(element).trigger("click");
    };
    additionalInformationPanel.closeFx = closeFx;
  };

  $.post(url, {id: resultId} ,showAdditionalInfo);
  
}

var showLoginWindow = function(){
    showLoadingLayer();
    var responseFunction = function(r)
    {
        hideLoadingLayer();
        r = JSON.parse(r);
        $(this).html(r.buttonString);
        if(!r.htmlString.trim() == "")
        {
          executeLoginJS(r);
        }
    };
    var url = getURL("login.php");
    $.post(url, {} ,responseFunction);
};
$("#loginButton").on("click", showLoginWindow);
  <?php
    if(checkUserLoggedIn()){
      echo "showProfieAndLogoutButtons();";
    }
  ?>

}

function addGoToProfile(){
  if($("#profileButton").length == 0){
    var profileButtonString = "<a id=\"profileButton\" href=\"#\" class=\"grayButton2\">Profile</a>";
    $("#loginButton").before(profileButtonString);    
  }
  $("#profileButton").on("click", function(){
    debugger;
    showLoadingLayer();
    var processResponse = function(r){
      var json = JSON.parse(r);
      if(json){
        if(json.response){
          $.post(url, {action: "showProfile"}, displayProfile);
        }else{
          configureLoginLayer(json);
          initializeProfileCompletion();
        }
      }
    };
    var params = {
      action: "requestProfile"
    };
    var url = getURL("profile.php");
    $.post(url, params, processResponse);    
  });
}
  